package com.hippo.javacore.multithreading;

/**
 * @ClassName ImplementRunnableCreateThread
 * @Description TODO 实现Runnable接口创建线程
 * @Author tangxl
 * @create 2023-03-10 11:39
 **/
public class ThreadDemo2 implements Runnable{
    private String name;

    ThreadDemo2(String name) {
        System.out.println("创建线程:"+name);
    }
    @Override
    public void run() {
        //获取当前线程对象
        Thread thread = Thread.currentThread();
        // 循环输出1~随机数
        int randomNumber = (int)(Math.random() * 100) + 1;
        for (int i = 0; i < randomNumber; i++) {
            System.out.println(thread.getName() +"输出"+i);
        }
    }

    public static void main(String[] args) {
        /**
         * 继承Thread类重写run()方法创建多线程：
         * 1.自己定义一个类继承Thread
         * 2.重写run()方法
         * 3.创建自己类对象
         * 4.创建一个Thread对象，并开启线程
         */
        // 创建了一个Thread对象，并将ThreadDemo2对象作为参数传递给它
        // 方式一:实现接口初始化
        Thread thread1 = new Thread(new ThreadDemo2("线程A"));
        // 方式二:匿名函数
        Runnable r = ()->{
            //获取当前线程对象
            Thread thread = Thread.currentThread();
            // 循环输出1~随机数
            int randomNumber = (int)(Math.random() * 100) + 1;
            for (int i = 0; i < randomNumber; i++) {
                System.out.println(thread.getName() +"输出"+i);
            }
        };
        Thread thread2 = new Thread(r);

        //给线程命名
        thread1.setName("线程A");
        thread2.setName("线程B");

        //开启线程
        thread1.start();
        thread2.start();
    }
}
